package com.blb.proxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGLib动态代理
 */
public class CGLibProductProxy implements MethodInterceptor {

    //被代理对象
    private Object target = null;

    public Object createProxy(Object target){
        this.target = target;
        //创建加强器
        Enhancer enhancer = new Enhancer();
        //设置父类
        enhancer.setSuperclass(target.getClass());
        //设置方法回调 MethodInterceptor的实例
        enhancer.setCallback(this);
        //生成代理对象
        Object obj = enhancer.create();
        return obj;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("这个产品真好！功能很牛逼！");
        //通过反射调用被代理对象的方法
        Object res = method.invoke(target,objects);
        System.out.println("我们提供售后服务，欢迎光临");
        return res;
    }
}
